package com.edol.painting.main;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doodle.common.crop.CropConstants;
import com.doodle.common.crop.SelectionPictureActivity;
import com.doodle.common.drawable.BlurDrawable;
import com.doodle.common.utils.Future;
import com.doodle.common.utils.FutureListener;
import com.doodle.common.utils.ThreadPool;
import com.doodle.common.utils.Utils;
import com.edol.painting.PainterConfig;
import com.edol.painting.R;
import com.edol.painting.data.PaintingDatabase;
import com.edol.painting.data.PaintingEntryLoader;
import com.edol.painting.painting.Brush;
import com.edol.painting.painting.Theme;
import com.edol.painting.utils.Constant;
import com.edol.painting.utils.PainterUtils;
import com.edol.painting.widget.BackgroundPaperContainer;
import com.edol.painting.widget.BrushAdjusterPreview;
import com.edol.painting.widget.BrushAdjusterView;
import com.edol.painting.widget.BrushPickerContainerView;
import com.edol.painting.widget.BrushToolContainerView;
import com.edol.painting.widget.ColorPickerView;
import com.edol.painting.widget.CommonDialog;
import com.edol.painting.widget.PaintView;
import com.edol.painting.widget.ProgressHUD;
import com.edol.painting.widget.TexturePickView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/7/4.
 */

public class PaintEditFragment extends Fragment implements
        LoaderManager.LoaderCallbacks<PaintingDatabase.PaintingEntry>, View.OnClickListener {

    private static final String TAG = "PaintingEditFragment";

    private static final int EDIT_PREVIEW_GONE = 1000;
    private static final int EDIT_BRUSH_TOOL_VISIBLE = 1001;
    private static final int EDIT_TOOLTIP_VISIBLE = 1002;
    private static final int EDIT_ON_BACK_PRESS = 1003;
    private static final int EDIT_UNDO = 1004;
    private static final int EDIT_REDO = 1005;
    private static final int EDIT_TOAST_MESSAGE = 1006;


    private static final int CHOOSE_PICTURE = 1110;

    private int mState = Constant.PAINTING_EDIT_TOAST_STATE_DEFAULT;

    private View mFragmentView;
    private PaintView mPaintView;
    private boolean mCheckPaintingLayers = true;

    private PopupWindow mEyeDropCancelView = null;

    private FrameLayout mBrushToolContainer;
    private BrushToolContainerView mBrushTool;

    private FrameLayout mBrushTypeContainer;
    private BrushPickerContainerView mBrushPicker;

    private LinearLayout mEraserContainer;
    private ImageView mHardEraser;
    private ImageView mSoftEraser;

    private LinearLayout mPaintTextureContainer;
    private ImageView mFillBg;
    private ImageView mSwitchBg;

    private long mId;
    private int mTheme;
    private int mCurrentTheme;

    private PaintingDatabase.PaintingEntry mPainting;
    private Rect mRect = new Rect();
    private boolean mAnimating = false;
    private boolean mIsOnPause = false;
    private boolean mShouldBack = false;

    private FrameLayout mColorPickerContainer;
    private boolean mColorPickerVisible = false;
    private ColorPickerView mColorPicker;
    private boolean mBrushAdjusterVisible = false;
    private BrushAdjusterView mBrushAdjustContainer;
    private boolean mEraserAdjusterVisible = false;
    private BrushAdjusterPreview mPreviewView;
    private FrameLayout mPreviewViewContainer;

    private HorizontalScrollView mBgPaperContainer;
    private BackgroundPaperContainer mBgPaperPicker;
    private FrameLayout mBgPaperColorPickContainer;
    private ColorPickerView mBgPaperColorPicker;
    private boolean mBgPaperPickerVisible;

    private LinearLayout mTexturePickContainer;
    private TexturePickView mTexturePickView;

    private boolean mIsClickRedoOrUndo = true;
    private ProgressHUD mLoadProgress;

    private SharedPreferences mPreference;

    private int mBrushType = Brush.BRUSH_PEN;
    private int mEraserType = Brush.BRUSH_ERASER;
    private int[] mBrushWidth = new int[Brush.BRUSH_COUNT];
    private int[] mBrushAlpha = new int[Brush.BRUSH_COUNT];
    private int mTextureAlpha = Constant.BRUSH_TEXTURE_ALPHA;

    private int mFillType = 0;

    private boolean mUseEraser = false;
    private boolean mEyeDropperVisible = false;
    private boolean mRedoIconVisible = false;

    private static final String COLOR_PICKER_VISIBLE_KEY = "color_picker_visible";
    private static final String BRUSH_ADJUSTER_VISIBLE_KEY = "brush_adjuster_visible";
    private static final String ERASER_ADJUSTER_VISIBLE_KEY = "eraser_adjuster_visible";
    private static final String REDO_ICON_VISIBLE_KEY = "redo_icon_visible";
    private static final String USE_ERASER_ICON_KEY = "use_eraser_icon";
    private static final String PAINTING_CURRENT_THEME_KEY = "painting_current_theme";

    private ImageView mPencilBrush;
    private ImageView mPenBrush;
    private ImageView mWcBrush;
    private ImageView mChalkBrush;
    private ImageView mMarkerBrush;
    private ImageView mScBrush;

    private ImageView mBackBtn;
    private ImageView mRedoBtn;
    private ImageView mUndoBtn;
    private ImageView mChangeBgBtn;
    private ImageView mInsertImgBtn;
    private ImageView mSaveBtn;

    //private boolean mNeedShowAd = false;

    private ColorPickerView.OnColorChangedListener mColorChangedListener = new ColorPickerView.OnColorChangedListener() {
        @Override
        public void colorChanged(int color) {
            if (!mBgPaperPickerVisible) {
                mBrushAdjustContainer.setCurrentColor(color);
                LayerDrawable ld = (LayerDrawable) mBrushTool.getColorPickView().getBackground();
                ld.getDrawable(1).setColorFilter(color, PorterDuff.Mode.SRC_IN);
            }
            if (mBgPaperPickerVisible) {
                mBgPaperColorPicker.setCurrentColor(mBgPaperColorPicker.getResultColor(), false);
            }
        }

        @Override
        public void onColorClicked(int color) {
            if (mBgPaperPickerVisible) {
                mPaintView.changeBgColor(color);
                mPainting.mTheme = color;
                mPaintView.setPainting(color);
                if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                    mPaintView.setBrush(mEraserType);
                    mPreviewView.setBrush(mPaintView.getBrush());
                }
            } else {
                int textureColor = mColorPicker.getSpecifyColor(mColorPicker.getRingUnit(), mColorPicker.getSquareUnitX(), 0.5f);
                mTexturePickView.setBitmapColor(textureColor);
                mTexturePickView.invalidate();
                if (mBrushTool.getItemFocus(R.id.action_brush)) {
                    mPaintView.setBrushColor(color);
                }
            }
        }
    };

    private PaintView.OnEyeDropperChangedListener mEyeDropperChangedListener = new PaintView.OnEyeDropperChangedListener() {
        @Override
        public void onEyeDropperStart() {
            mEyeDropperVisible = true;
            setBrushToolVisibility(false);
            setEraserContainerVisible(false);
            setColorPickerVisibility(false);
            setTexturePickerVisibility(false);
            setBgPaperColorPickerVisibility(false);
            setPaperContainerVisibility(false);

            setBushAllToolVisibility(false);

            showEyeCancelPopUp();
        }

        @Override
        public void onEyeDropperEnd(int color, boolean cancel) {
            mEyeDropperVisible = false;
            if (mUseEraser) {
                mUseEraser = false;
                // applyBrushSetting();
                // updateIcon();
            }
            if (cancel) {
                if (mBrushTool.getItemFocus(R.id.action_brush)) {
                    mPaintView.setBrushColor(color);
                }
                mBrushAdjustContainer.setCurrentColor(color);
                int textureColor = mColorPicker.getSpecifyColor(mColorPicker.getRingUnit(), mColorPicker.getSquareUnitX(), 0.5f);
                mTexturePickView.setBitmapColor(textureColor);
                mTexturePickView.invalidate();
                LayerDrawable ld = (LayerDrawable) mBrushTool.getColorPickView().getBackground();
                ld.getDrawable(1).setColorFilter(color, PorterDuff.Mode.SRC_IN);
            }
            setBushAllToolVisibility(true);
            dismissEyeDropCancelView();
        }

        @Override
        public void onEyeDropperColorChanged(int color, boolean dropOK) {
            mBrushAdjustContainer.invalidatePreview();
            if (!dropOK) {
                updateEyeDropCancelView(0xFFFF6600, Color.WHITE);
            } else {
                updateEyeDropCancelView(Color.WHITE, Color.BLACK);
            }
        }
    };

    private PaintView.PaintStateListener mPaintStateListener = new PaintView.PaintStateListener() {
        @Override
        public void onRouteStateChanged() {
            if (mUndoBtn != null) {
                if (mUndoBtn.isEnabled()) {
                    if (!mPaintView.canUndo() || mPaintView.getInCutCommit() || mPaintView.getInTextureCommit() || mPaintView.inInsertImage()) {
                        mUndoBtn.setEnabled(false);
                        mUndoBtn.setAlpha(76);
                    }
                } else {
                    if (mPaintView.canUndo() && !mPaintView.getInCutCommit() && !mPaintView.getInTextureCommit() && !mPaintView.inInsertImage()) {
                        mUndoBtn.setEnabled(true);
                        mUndoBtn.setAlpha(255);
                    }
                }
            }
            isOnClickRedoMenuItem();
        }

        @Override
        public void onSingleTapUp() {
            if (mBgPaperContainer != null && mBgPaperContainer.getVisibility() == View.VISIBLE) {
                setPaperContainerVisibility(false);
            } else if (mBgPaperPickerVisible) {
                setBgPaperColorPickerVisibility(false);
            } else {
                setBushAllToolVisible();
            }
        }

        @Override
        public void onDownPaintView() {
            if (mBrushTool.getItemFocus(R.id.action_brush)) {
                mBrushTool.updateItemView(R.id.action_brush);
            }
            if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                mBrushTool.updateItemView(R.id.action_eraser);
            }
            if (mBrushTool.getItemFocus(R.id.action_texture)) {
                mBrushTool.updateItemView(R.id.action_texture);
            }
            if (mBrushTool.getItemFocus(R.id.action_cut)) {
                mBrushTool.updateItemView(R.id.action_cut);
            }
        }

        @Override
        public void onEditUp() {
        }

        @Override
        public void onTouchDown() {
            mBrushTool.setControlsEnabled(false);
            mBrushAdjustContainer.setSeekBarEnabled(false);
            mPreviewHandler.sendEmptyMessageDelayed(EDIT_PREVIEW_GONE, 150);
        }

        @Override
        public void onTouchUp() {
            mBrushTool.setControlsEnabled(true);
            mBrushAdjustContainer.setSeekBarEnabled(true);
        }

        @Override
        public void onInsertFinish() {
            mInsertImgBtn.setEnabled(true);
            if (mCheckPaintingLayers) {
                mChangeBgBtn.setEnabled(true);
            }
            mPaintStateListener.onRouteStateChanged();
        }
    };

    private BrushAdjusterView.OnBrushWidthChangedListener mBrushWidthChangeListener = new BrushAdjusterView.OnBrushWidthChangedListener() {
        @Override
        public void brushWidthChanged(int brushWidth) {
            mPaintView.commitInsert();
            setPreviewContainerVisiable(true);
        }

        @Override
        public void brushWidthEnd(int brushWidth) {
            setPreviewContainerVisiable(false);
            brushWidth = Math.max(1, brushWidth);
            int mCurrrentBrushType = Utils.clamp(mPaintView.getBrushType(), Brush.BRUSH_ERASER, Brush.BRUSH_COUNT - 1);
            mBrushWidth[mCurrrentBrushType] = brushWidth;
            if (mPaintView != null) {
                mPaintView.setBrushWidth(brushWidth);
            }
        }
    };

    private BrushAdjusterView.OnBrushAlphaChangedListener mBrushAlphaChangeListener = new BrushAdjusterView.OnBrushAlphaChangedListener() {
        @Override
        public void brushAlphaChanged(int brushAlpha) {
            mPaintView.commitInsert();
            setPreviewContainerVisiable(true);
        }

        @Override
        public void brushAlphaEnd(int brushAlpha) {
            setPreviewContainerVisiable(false);
            brushAlpha = Math.max(0, brushAlpha);
            if (!mBrushTool.getItemFocus(R.id.action_texture)) {
                int mCurrrentBrushType = Utils.clamp(mPaintView.getBrushType(), Brush.BRUSH_ERASER, Brush.BRUSH_COUNT - 1);
                mBrushAlpha[mCurrrentBrushType] = brushAlpha;
            } else {
                mTextureAlpha = brushAlpha;
            }
            if (mPaintView != null) {
                mPaintView.setBrushAlpha(brushAlpha);
            }
        }
    };

    private BrushPickerContainerView.OnBrushTypeChangedListener myBrushTypeChangedListener = new BrushPickerContainerView.OnBrushTypeChangedListener() {
        @Override
        public void brushTypeChanged(int type) {
            if (mBrushType != type) {
                mBrushType = type;
                applyBrushTypeSetting();
                mBrushTool.updateBrushIcon(mBrushType);
                mPreviewView.invalidate();
            }
        }
    };

    private AnimatorListenerAdapter mPreviewContainerAnimatorListener = new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mPreviewViewContainer.setVisibility(View.GONE);
        }

    };

    private TexturePickView.OnChildClickListener mTexturePickViewClickListener = new TexturePickView.OnChildClickListener() {
        @Override
        public void onTextureChildClick(int position, Shader shader) {
            mPaintView.setTextureShader(shader);
            mPreviewView.setBrushShader(shader);
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        setFullScreen(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //setFullScreen(true);
        setHasOptionsMenu(true);

        mId = -1;
        Bundle args = getArguments();
        if (args != null) {
            mId = args.getLong(Constant.ARG_KEY_PAINTING_ID, -1);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        PaintController.getInstances().hideActionBar(getActivity());
        PaintController.getInstances().lockDrawer(getActivity());

        getLoaderManager().initLoader(0, getArguments(), this);

        /*if (!YouMi.mSplashAdShowed) {
            mNeedShowAd = true;
            YouMi.mSplashAdShowed = true;
            YouMi.setupSpotAd(getActivity());
        }*/

        showGuide();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mFragmentView == null || mFragmentView.getParent() != null) {
            mFragmentView = inflater.inflate(R.layout.fragment_paint_edit, container, false);
            initView(mFragmentView);
        }

        return mFragmentView;
    }

    private void showGuide() {
        SharedPreferences preferences = getActivity().getSharedPreferences(PainterConfig.PACKAGE_NAME, 0);
        boolean hasShown = preferences.getBoolean(Constant.GUIDE_COLOR_PICKER, false);
        if (!hasShown) {
            preferences.edit().putBoolean(Constant.GUIDE_COLOR_PICKER, true).apply();
            final PopupWindow window = new PopupWindow(getActivity());
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_guide_color_picker, null);
            view.findViewById(R.id.close_guide).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                }
            });

            window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            window.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            window.setBackgroundDrawable(new ColorDrawable(0x66000000));
            window.setContentView(view);
            window.setOutsideTouchable(true);
            window.setFocusable(true);
            window.showAtLocation(mPaintView, Gravity.CENTER, 0, 0);
        }
    }

    private void setFullScreen(boolean enter) {
        if (enter) {
            WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getActivity().getWindow().setAttributes(lp);
        } else {
            WindowManager.LayoutParams attr = getActivity().getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getActivity().getWindow().setAttributes(attr);
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    private LayerDrawable getCreateContainerBackground() {
        Drawable[] layer = new Drawable[2];
        layer[0] = new BlurDrawable();
        layer[1] = getResources().getDrawable(R.drawable.blur_drawable_border);
        LayerDrawable layerDrawable = new LayerDrawable(layer);
        return layerDrawable;
    }

    private void initView(View parent) {
        mPaintView = (PaintView) parent.findViewById(R.id.paint_view);
        mPaintView.setPaintStateListener(mPaintStateListener);
        mPaintView.setPaintMode(mId >= 0 ? PaintView.PAINT_MODE_EDIT : PaintView.PAINT_MODE_NEW);

        mColorPickerContainer = (FrameLayout) parent.findViewById(R.id.color_picker_container);
        //mColorPickerContainer.setBackground(getCreateContainerBackground());
        mColorPicker = (ColorPickerView) parent.findViewById(R.id.color_picker);
        mColorPicker.setOnColorChangedListener(mColorChangedListener);
        mPaintView.setColorPicker(mColorPicker);

        mBrushToolContainer = (FrameLayout) parent.findViewById(R.id.brush_tool);
        mBrushTool = (BrushToolContainerView) parent.findViewById(R.id.painter_tool_container);
        mBrushTool.setOnItemClickListener(this);

        mPreviewViewContainer = (FrameLayout) parent.findViewById(R.id.brush_preview_container);
        mPreviewView = (BrushAdjusterPreview) parent.findViewById(R.id.brush_preview);
        ViewGroup.LayoutParams lp = mPreviewView.getLayoutParams();
        lp.width = getResources().getDimensionPixelSize(R.dimen.preview_width);
        lp.height = getResources().getDimensionPixelSize(R.dimen.preview_height);

        mBrushTypeContainer = (FrameLayout) parent.findViewById(R.id.brush_container);
        int brushTypeMarginLeft = (int) getResources().getDimensionPixelSize(R.dimen.brush_container_padding_left);
        //int brushTypeMarginBottom = (int) getResources().getDimensionPixelSize(R.dimen.all_tool_container_padding_bottom);
        RelativeLayout.LayoutParams lpt = (RelativeLayout.LayoutParams) mBrushTypeContainer.getLayoutParams();
        lpt.leftMargin = brushTypeMarginLeft;
        //lpt.bottomMargin = brushTypeMarginBottom;
        //mBrushTypeContainer.setBackground(getCreateContainerBackground());
        mBrushPicker = (BrushPickerContainerView) parent.findViewById(R.id.brush_picker_container);
        mBrushPicker.setBrushTypeChangeListener(myBrushTypeChangedListener);

        mEraserContainer = (LinearLayout) parent.findViewById(R.id.eraser_container);
        //mEraserContainer.setBackground(getCreateContainerBackground());

        int radius = getResources().getDimensionPixelSize(R.dimen.painting_edit_color_pick_ring_radius);
        int innerRadius = getResources().getDimensionPixelSize(R.dimen.painting_edit_color_pick_inner_ring_radius);
        int width = getResources().getDimensionPixelSize(R.dimen.painting_edit_color_pick_seekbar_width);
        int height = getResources().getDimensionPixelSize(R.dimen.painting_edit_color_pick_seekbar_height);
        int padding = getResources().getDimensionPixelSize(R.dimen.painting_edit_color_pick_padding);

        mColorPicker.setPadding(padding, padding, padding, padding);
        mColorPicker.setColorRingDimen(radius, innerRadius);
        mColorPicker.setSeekBarSize(width, height);

        mPaintTextureContainer = (LinearLayout) parent.findViewById(R.id.paint_bg_container);
        mFillBg = (ImageView) parent.findViewById(R.id.fill_bg);
        mSwitchBg = (ImageView) parent.findViewById(R.id.switch_bg);

        mPaintView.setOnEyeDropperChangedListener(mEyeDropperChangedListener);

        mBrushAdjustContainer = (BrushAdjusterView) parent.findViewById(R.id.painter_brush_adjust);
        mBrushAdjustContainer.inflateView(parent);
        mBrushAdjustContainer.setBrushWidthChangedListener(mBrushWidthChangeListener);
        mBrushAdjustContainer.setBrushAlphaChangedListener(mBrushAlphaChangeListener);
        mBrushAdjustContainer.setPreview(mPreviewView);

        mBgPaperColorPickContainer = (FrameLayout) parent.findViewById(R.id.bg_paper_color_picker_container);
        //mBgPaperColorPickContainer.setBackground(getCreateContainerBackground());
        mBgPaperColorPicker = (ColorPickerView) mBgPaperColorPickContainer.findViewById(R.id.bg_paper_color_picker);
        mBgPaperColorPicker.setOnColorChangedListener(mColorChangedListener);
        mBgPaperColorPicker.setPadding(padding, padding, padding, padding);
        mBgPaperColorPicker.setColorRingDimen(radius, innerRadius);
        mBgPaperColorPicker.setSeekBarSize(width, height);

        mTexturePickContainer = (LinearLayout) parent.findViewById(R.id.texture_picker_container);
        //mTexturePickContainer.setBackgroundDrawable(new BlurDrawable());
        mTexturePickView = (TexturePickView) parent.findViewById(R.id.texture_picker);
        mTexturePickView.setBitmapColor(mColorPicker.getResultColor());
        mTexturePickView.setOnChildClickListener(mTexturePickViewClickListener);

        mBackBtn = (ImageView) parent.findViewById(R.id.back);
        mRedoBtn = (ImageView) parent.findViewById(R.id.redo);
        mUndoBtn = (ImageView) parent.findViewById(R.id.undo);
        mChangeBgBtn = (ImageView) parent.findViewById(R.id.change_bg);
        mInsertImgBtn = (ImageView) parent.findViewById(R.id.insert_img);
        mSaveBtn = (ImageView) parent.findViewById(R.id.save);

        mFillBg.setOnClickListener(this);
        mSwitchBg.setOnClickListener(this);

        mBackBtn.setOnClickListener(this);
        mRedoBtn.setOnClickListener(this);
        mUndoBtn.setOnClickListener(this);
        mChangeBgBtn.setOnClickListener(this);
        mInsertImgBtn.setOnClickListener(this);
        mSaveBtn.setOnClickListener(this);

        setBushAllToolVisible();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(COLOR_PICKER_VISIBLE_KEY, mColorPickerVisible);
        outState.putBoolean(BRUSH_ADJUSTER_VISIBLE_KEY, mBrushAdjusterVisible);
        outState.putBoolean(ERASER_ADJUSTER_VISIBLE_KEY, mEraserAdjusterVisible);
        outState.putBoolean(REDO_ICON_VISIBLE_KEY, mRedoIconVisible);
        outState.putBoolean(USE_ERASER_ICON_KEY, mUseEraser);
        outState.putInt(PAINTING_CURRENT_THEME_KEY, mPaintView.getCurrentTheme());
    }

    private boolean isDestroyActivity = false;

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mColorPickerVisible = savedInstanceState.getBoolean(COLOR_PICKER_VISIBLE_KEY, false);
            mBrushAdjusterVisible = savedInstanceState.getBoolean(BRUSH_ADJUSTER_VISIBLE_KEY, false);
            mEraserAdjusterVisible = savedInstanceState.getBoolean(ERASER_ADJUSTER_VISIBLE_KEY, false);
            mRedoIconVisible = savedInstanceState.getBoolean(REDO_ICON_VISIBLE_KEY, false);
            mUseEraser = savedInstanceState.getBoolean(USE_ERASER_ICON_KEY, false);
            mCurrentTheme = savedInstanceState.getInt(PAINTING_CURRENT_THEME_KEY, -1);
            mPaintView.setBackgroundDrawable(getResources().getDrawable(R.color.paintview_background_color));
            isDestroyActivity = true;
        }
        super.onViewStateRestored(savedInstanceState);
    }

    private void isOnClickRedoMenuItem() {
        if (mRedoBtn != null) {
            if (mRedoBtn.isEnabled()) {
                if (!mPaintView.canRedo() || mPaintView.getInCutCommit() || mPaintView.getInTextureCommit() || mPaintView.inInsertImage()) {
                    mRedoBtn.setEnabled(false);
                    mRedoBtn.setAlpha(76);
                }
            } else {
                if (mPaintView.canRedo() && !mPaintView.getInCutCommit() && !mPaintView.getInTextureCommit() && !mPaintView.inInsertImage()) {
                    mRedoBtn.setEnabled(true);
                    mRedoBtn.setAlpha(255);
                }
            }
        }
    }

    /*private void gotoGalleryPickImage() {
        File tmpFile = PainterUtils.createNewPaintingFile(getActivity().getApplicationContext(), System.currentTimeMillis(), false);
        if (tmpFile == null) {
            return;
        }
        imageUri = Uri.fromFile(tmpFile);
        Log.i("liu", "imageUri=" + imageUri);
        // if get from gallery return the file content uri,
        // if get from camera return the imageUri that we set,
        // if get from file manager then return the file uri.
        Intent intent = new Intent("meizu.intent.action.PICK", imageUri);
        try {
            intent.setComponent(new ComponentName("com.android.gallery3d", "com.android.gallery3d.app.Gallery"));
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image*//*");
            startActivityForResult(intent, CHOOSE_PICTURE);
        } catch (ActivityNotFoundException e) {

        }
    }*/

    private void gotoGalleryPickImage() {
        Context context = getActivity();
        File tmpFile = PainterUtils.createNewPaintingFile(context.getApplicationContext(), System.currentTimeMillis(), false);
        if (tmpFile == null) {
            return;
        }
        imageUri = Uri.fromFile(tmpFile);

        Intent intent = new Intent(
                Intent.ACTION_GET_CONTENT,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            startActivityForResult(intent, CHOOSE_PICTURE);
        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                startActivityForResult(intent, CHOOSE_PICTURE);
            } else {
                //如手机没有找到默认打开图片的应用(比如用户没有安装图库)，让用户自己选择打开图片的应用程序
                intent = new Intent(
                        Intent.ACTION_GET_CONTENT,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("*/*");
                startActivityForResult(intent, CHOOSE_PICTURE);
            }
        }
    }

    private void selectionPic() {
        Intent i = new Intent(getContext(), SelectionPictureActivity.class);
        i.putExtra(CropConstants.NEED_CROP, false);
        startActivityForResult(i, CHOOSE_PICTURE);
    }


    private Uri imageUri = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CHOOSE_PICTURE && resultCode == Activity.RESULT_OK) {
            if (data != null && data.getData() != null) {
                final Uri uri = data.getData();
                ThreadPool.getInstance().submit(new ThreadPool.Job<Bitmap>() {
                    @Override
                    public Bitmap run(ThreadPool.JobContext jc) {
                        if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme()) ||
                                ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
                            int rotation = 0;
                            try {
                                InputStream is = getActivity().getContentResolver().openInputStream(uri);
                                rotation = PainterUtils.getOrientation(is);
                                Utils.closeSilently(is);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            Bitmap bitmap = null;
                            Bitmap b = null;
                            try {
                                InputStream is = getActivity().getContentResolver().openInputStream(uri);

                                BitmapFactory.Options op = new BitmapFactory.Options();//图片放缩
                                op.inMutable = true;
                                op.inSampleSize = 2;
                                b = BitmapFactory.decodeStream(is, null, op);
                                Utils.closeSilently(is);
                                int w = getResources().getDimensionPixelSize(R.dimen.painting_edit_insert_picture_width);
                                int h = 0;
                                if (rotation != 0) {
                                    Matrix matrix = new Matrix();
                                    matrix.setRotate(rotation);
                                    Bitmap p = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
                                    b.recycle();
                                    b = null;
                                    h = w * p.getHeight() / p.getWidth();
                                    bitmap = Bitmap.createScaledBitmap(p, w, h, true);
                                    p.recycle();
                                    p = null;
                                } else {
                                    h = w * b.getHeight() / b.getWidth();
                                    bitmap = Bitmap.createScaledBitmap(b, w, h, true);
                                    b.recycle();
                                    b = null;
                                }
                            } catch (OutOfMemoryError e) {
                                Log.w(TAG, "Insert Picture OutOfMemoryError");
                                mState = Constant.PAINTING_EDIT_TOAST_STATE_INSERT_FAIL;
                                mPreviewHandler.sendEmptyMessage(EDIT_TOAST_MESSAGE);
                                return null;
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            return bitmap;
                        }
                        return null;
                    }
                }, new FutureListener<Bitmap>() {
                    @Override
                    public void onFutureDone(Future<Bitmap> future) {
                        final Bitmap bitmap = future == null ? null : future.get();
                        Activity a = getActivity();
                        if (a != null) {
                            a.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (bitmap != null) {
                                        mPaintView.initAndShowInsertImage(bitmap);
                                        mPaintStateListener.onRouteStateChanged();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        } else {
            mInsertImgBtn.setEnabled(true);
            //TODO
            //mCopyBtn.setEnabled(true);
            if (mCheckPaintingLayers) {
                mChangeBgBtn.setEnabled(true);
            }
            mPaintStateListener.onRouteStateChanged();
        }
    }

    private void handlePickerImg() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mIsOnPause = false;
        mPreference = getActivity().getPreferences(0);

        float brushRingUnit = mPreference.getFloat(Constant.PREF_BRUSH_COLOR_RING_UNIT, 0);
        float brushSquareUnitX = mPreference.getFloat(Constant.PREF_BRUSH_COLOR_SQUARE_UNIT_X, 0.1f);
        float brushSquareUnitY = mPreference.getFloat(Constant.PREF_BRUSH_COLOR_SQUARE_UNIT_Y, 0.9f);
        mColorPicker.setCurrentColor(brushRingUnit, brushSquareUnitX, brushSquareUnitY);
        int oldColor = mPreference.getInt(Constant.PREF_BRUSH_OLD_COLOR, mColorPicker.getResultColor());
        mColorPicker.setCurrentColor(oldColor, false);
        //mColorPicker.setCurrentColor(mColorPicker.getResultColor(), false);

        float editBgRingUnit = mPreference.getFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_RING_UNIT, 0);
        float editBgSquareUnitX = mPreference.getFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_SQUARE_UNIT_X, 0.1f);
        float editBgSquareUnitY = mPreference.getFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_SQUARE_UNIT_Y, 0.9f);
        mBgPaperColorPicker.setCurrentColor(editBgRingUnit, editBgSquareUnitX, editBgSquareUnitY);

        mBrushType = mPreference.getInt(Constant.PREF_BRUSH_TYPE, Brush.BRUSH_PEN);
        mEraserType = mPreference.getInt(Constant.PREF_ERASER_TYPE, Brush.BRUSH_ERASER);
        if (mEraserType > 7) mEraserType = 7;
        for (int i = 0; i < Brush.BRUSH_COUNT; ++i) {
            mBrushWidth[i] = mPreference.getInt(Constant.PREF_BRUSH_WIDTH + i, PaintEditConfig.sBrushDefaultWidth[i]);
            mBrushAlpha[i] = mPreference.getInt(Constant.PREF_BRUSH_ALPHA + i, PaintEditConfig.sBrushDefaultAlpha[i]);
        }

        mFillType = mPreference.getInt(Constant.PREF_FILL_TYPE, 0);

        if (mBrushType < 0 || mBrushType > Brush.BRUSH_LAST || mBrushType == Brush.BRUSH_ERASER || mBrushType == Brush.BRUSH_SOFT_ERASRE) {
            mBrushType = Brush.BRUSH_PEN;
        }

        // init the brush adjuster
        mBrushAdjustContainer.setCurrentColor(mColorPicker.getResultColor());

        mBrushPicker.setBrushType(mBrushType);

        mTexturePickView.setSelectIdx(mFillType);
        int textureColor = mColorPicker.getSpecifyColor(mColorPicker.getRingUnit(), mColorPicker.getSquareUnitX(), 0.5f);
        mTexturePickView.setBitmapColor(textureColor);
        mTextureAlpha = mPreference.getInt(Constant.PREF_TEXTURE_ALPHA, Constant.BRUSH_TEXTURE_ALPHA);

        //updateIcon();
        mBrushTool.updateEraserIcon(mEraserType);
        mBrushTool.updateBrushIcon(mBrushType);
        LayerDrawable ld = (LayerDrawable) mBrushTool.getColorPickView().getBackground();
        ld.getDrawable(1).setColorFilter(mColorPicker.getResultColor(), PorterDuff.Mode.SRC_IN);
        if (mShouldBack) {
            mShouldBack = false;
            mPreviewHandler.sendEmptyMessageDelayed(EDIT_ON_BACK_PRESS, 500);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsOnPause = true;
        if (mPaintView != null && mPaintView.getBrush() != null) {
            SharedPreferences.Editor editor = mPreference.edit();
            editor.putFloat(Constant.PREF_BRUSH_COLOR_RING_UNIT, mColorPicker.getRingUnit())
                    .putFloat(Constant.PREF_BRUSH_COLOR_SQUARE_UNIT_X, mColorPicker.getSquareUnitX())
                    .putFloat(Constant.PREF_BRUSH_COLOR_SQUARE_UNIT_Y, mColorPicker.getSquareUnitY())
                    .putInt(Constant.PREF_BRUSH_OLD_COLOR, mColorPicker.getOldColor())
                    .putInt(Constant.PREF_BRUSH_TYPE, mBrushType)
                    .putInt(Constant.PREF_ERASER_TYPE, mEraserType);
            editor.putFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_RING_UNIT, mBgPaperColorPicker.getRingUnit())
                    .putFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_SQUARE_UNIT_X, mBgPaperColorPicker.getSquareUnitX())
                    .putFloat(Constant.PREF_EDIT_BACKGROUND_COLOR_SQUARE_UNIT_Y, mBgPaperColorPicker.getSquareUnitY());
            for (int i = 0; i < Brush.BRUSH_COUNT; ++i) {
                editor.putInt(Constant.PREF_BRUSH_WIDTH + i, mBrushWidth[i]);
                editor.putInt(Constant.PREF_BRUSH_ALPHA + i, mBrushAlpha[i]);
            }
            editor.putInt(Constant.PREF_FILL_TYPE, mTexturePickView.getSelectIdx())
                    .putInt(Constant.PREF_TEXTURE_ALPHA, mTextureAlpha);
            editor.commit();
        }
        setPreviewContainerVisiable(false);
        dismissEyeDropCancelView();

        // 插屏广告
        /*if (mNeedShowAd) {
            SpotManager.getInstance(getActivity()).onPause();
        }*/
    }

    @Override
    public void onStop() {
        if (mRect.isEmpty()) {
            //TODO
        }
        super.onStop();

        // 插屏广告
        /*if (mNeedShowAd) {
            SpotManager.getInstance(getActivity()).onStop();
        }*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPreviewHandler.removeCallbacksAndMessages(null);
        if (mBgPaperPicker != null) {
            mBgPaperPicker.clear();
        }
        mPreviewView.clear();
        mBrushAdjustContainer.clear();
        mBrushTool.clear();
        mPaintView.clear();

        setFullScreen(false);

        if (mId == -1) {
            PaintController.getInstances().showActionBar(getActivity());
            PaintController.getInstances().unlockDrawer(getActivity());
        }
        // 插屏广告
       /* if (mNeedShowAd) {
            mNeedShowAd = false;
            SpotManager.getInstance(getActivity()).onDestroy();
        }*/
    }

    private void applyBrushTypeSetting() {
        mPaintView.setBrush(mBrushType);
        mPaintView.setBrushWidth(mBrushWidth[mBrushType]);
        mPaintView.setBrushAlpha(mBrushAlpha[mBrushType]);
        mPaintView.setBrushColor(mColorPicker.getResultColor());

        // mBrushAdjustContainer.setBrushType(mBrushType);
        mBrushAdjustContainer.setBrushWidthRange(PaintEditConfig.sBrushMinWidth[mBrushType], PaintEditConfig.sBrushMaxWidth[mBrushType]);
        mBrushAdjustContainer.setBrushAlphaRange(PaintEditConfig.sBrushMinAlpha[mBrushType], PaintEditConfig.sBrushMaxAlpha[mBrushType]);
        mBrushAdjustContainer.initialBrushStatus(mBrushWidth[mBrushType], mBrushAlpha[mBrushType]);

        mPreviewView.setBrush(mPaintView.getBrush());
    }

    private void applyEraserTypeSetting() {
        if (mEraserType > 7) mEraserType = 7;
        mPaintView.setBrush(mEraserType);
        mPaintView.setBrushWidth(mBrushWidth[mEraserType]);
        mPaintView.setBrushAlpha(mBrushAlpha[mEraserType]);

        // mBrushAdjustContainer.setBrushType(mEraserType);
        mBrushAdjustContainer.setBrushWidthRange(PaintEditConfig.sBrushMinWidth[mEraserType], PaintEditConfig.sBrushMaxWidth[mEraserType]);
        mBrushAdjustContainer.setBrushAlphaRange(PaintEditConfig.sBrushMinAlpha[mEraserType], PaintEditConfig.sBrushMaxAlpha[mEraserType]);
        mBrushAdjustContainer.initialBrushStatus(mBrushWidth[mEraserType], mBrushAlpha[mEraserType]);

        mPreviewView.setBrush(mPaintView.getBrush());
    }

    private void applyTextureTypeSetting() {
        mPaintView.initFillTexture(mTexturePickView.getCurrentTexture());
        mPaintView.setBrushAlpha(mTextureAlpha);
        mBrushAdjustContainer.setBrushAlphaRange(PaintEditConfig.sBrushTextureAlpha[Brush.TEXTURE_MIN_ALPHA], PaintEditConfig.sBrushTextureAlpha[Brush.TEXTURE_MAX_ALPHA]);
        mBrushAdjustContainer.initialBrushAlpha(mTextureAlpha);

        mPreviewView.setBrushShader(mTexturePickView.getCurrentTexture());
        mPreviewView.setBrushColor(mColorPicker.getResultColor());
    }

    private void setBushAllToolVisible() {
        if (mBrushToolContainer.getVisibility() != View.VISIBLE) {
            setBrushToolVisibility(false);
            setEraserContainerVisible(false);
            setColorPickerVisibility(false);
            setTexturePickerVisibility(false);
            setFillBgContainerVisible(false);

            mBrushToolContainer.setVisibility(View.VISIBLE);
            if (!mBrushTool.getItemFocus(R.id.action_cut)) {
                setBrushAdjustContainerVisibility(true);
            }
        } else {
            if (mBrushTypeContainer.getVisibility() == View.VISIBLE) {
                mBrushTypeContainer.setVisibility(View.GONE);
            } else if (mEraserContainer.getVisibility() == View.VISIBLE) {
                mEraserContainer.setVisibility(View.GONE);
            } else if (mColorPickerContainer.getVisibility() == View.VISIBLE) {
                mColorPickerContainer.setVisibility(View.GONE);
            } else if (mTexturePickContainer.getVisibility() == View.VISIBLE) {
                mTexturePickContainer.setVisibility(View.GONE);
            } else if (mPaintTextureContainer.getVisibility() == View.VISIBLE) {
                mPaintTextureContainer.setVisibility(View.GONE);
            }else {
                mBrushToolContainer.setVisibility(View.GONE);
                setBrushAdjustContainerVisibility(false);
            }
        }
    }

    private void setBushAllToolVisibility(boolean visible) {
        if (mBrushToolContainer.getVisibility() == View.VISIBLE && !visible) {
            mBrushToolContainer.setVisibility(View.INVISIBLE);
            mBrushAdjustContainer.setVisibility(View.INVISIBLE);
        } else if (mBrushToolContainer.getVisibility() == View.INVISIBLE && visible) {
            mBrushToolContainer.setVisibility(View.VISIBLE);
            mBrushAdjustContainer.setVisibility(View.VISIBLE);
        }
    }

    private void setBrushToolVisibility(boolean visible) {
        boolean isShow = mBrushTypeContainer.getVisibility() == View.VISIBLE;
        if (isShow && !visible) {// if current is show
            mBrushTypeContainer.setVisibility(View.GONE);
        } else if (!isShow && visible) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
                mBrushTypeContainer.setVisibility(View.VISIBLE);
                mBrushTool.updateItemView(R.id.action_brush);
            } else if (mBrushTool.getItemFocus(R.id.action_brush)) {
                mBrushTypeContainer.setVisibility(View.VISIBLE);
            } else {
                mBrushTool.updateItemView(R.id.action_brush);
            }
        }
    }

    private void setEraserContainerVisible(boolean visible) {
        boolean isShow = mEraserContainer.getVisibility() == View.VISIBLE;
        if (isShow && !visible) {// if current is show
            mEraserContainer.setVisibility(View.GONE);
        } else if (!isShow && visible) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
                mEraserContainer.setVisibility(View.VISIBLE);
                mBrushTool.updateItemView(R.id.action_eraser);
            } else if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                mEraserContainer.setVisibility(View.VISIBLE);
            } else {
                mBrushTool.updateItemView(R.id.action_eraser);
            }
        }
    }

    private void setFillBgContainerVisible(boolean visible) {
        boolean isShow = mTexturePickContainer.getVisibility() == View.VISIBLE;
        if (isShow && !visible) {// if current is show
            mTexturePickContainer.setVisibility(View.GONE);
        } else if (!isShow && visible) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
                mTexturePickContainer.setVisibility(View.VISIBLE);
                mTexturePickContainer.invalidate();
                mBrushTool.updateItemView(R.id.action_texture);
            } else if (mBrushTool.getItemFocus(R.id.action_texture)) {
                mTexturePickContainer.setVisibility(View.VISIBLE);
                mTexturePickContainer.invalidate();
            } else {
                mBrushTool.updateItemView(R.id.action_texture);
            }
        }
    }

    private void setBgPaperColorPickerVisibility(boolean visible) {
        boolean isShow = mBgPaperColorPickContainer.getVisibility() == View.VISIBLE;
        if (visible && !isShow) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
            }
            mBgPaperPickerVisible = true;
            mBgPaperColorPickContainer.animate().cancel();
            mBgPaperColorPickContainer.setVisibility(View.VISIBLE);
        } else if (isShow && !visible) {
            mBgPaperPickerVisible = false;
            mBgPaperColorPickContainer.setVisibility(View.GONE);
        }
    }

    private void setColorPickerVisibility(boolean visible) {
        boolean isShow = mColorPickerContainer.getVisibility() == View.VISIBLE;
        if (visible && !isShow) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
            }
            mBrushTool.updateItemView(R.id.action_color_picker);

            mColorPickerContainer.animate().cancel();
            mColorPickerContainer.setVisibility(View.VISIBLE);
        } else if (isShow && !visible) {
            mColorPickerContainer.setVisibility(View.GONE);
        }
    }

    private View getSecondaryVisibleView() {
        if (mBrushTypeContainer.getVisibility() == View.VISIBLE) {
            return mBrushTypeContainer;
        }

        if (mTexturePickContainer.getVisibility() == View.VISIBLE) {
            return mTexturePickContainer;
        }

        if (mEraserContainer.getVisibility() == View.VISIBLE) {
            return mEraserContainer;
        }
        if (mBgPaperContainer != null && mBgPaperContainer.getVisibility() == View.VISIBLE) {
            return mBgPaperContainer;
        }
        if (mColorPickerContainer.getVisibility() == View.VISIBLE) {
            return mColorPickerContainer;
        }
        if (mBgPaperColorPickContainer.getVisibility() == View.VISIBLE) {
            mBgPaperPickerVisible = false;
            return mBgPaperColorPickContainer;
        }
        if (mTexturePickContainer.getVisibility() == View.VISIBLE) {
            return mTexturePickContainer;
        }
        return null;
    }

    private void showEyeCancelPopUp() {
        if (mEyeDropCancelView == null) {
            LinearLayout layout = new LinearLayout(getActivity().getApplicationContext());
            layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            layout.setGravity(Gravity.CENTER);
            layout.setBackgroundColor(Color.WHITE);
            TextView tv = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.paint_eye_txt, null);
            layout.addView(tv);

            mEyeDropCancelView = new PopupWindow(layout, Constant.PAINTING_WIDTH, Constant.ACTIONBAR_HEIGHT);
            mEyeDropCancelView.setFocusable(false);
            mEyeDropCancelView.setOutsideTouchable(false);
            mEyeDropCancelView.setBackgroundDrawable(null);
        }
        mEyeDropCancelView.showAtLocation(mBrushToolContainer, Gravity.NO_GRAVITY, 0, Constant.PAINTING_HEIGHT);
    }

    private void updateEyeDropCancelView(int bgColor, int textColor) {
        if (mEyeDropCancelView != null) {
            mEyeDropCancelView.getContentView().setBackgroundColor(bgColor);
            TextView ttv = (TextView) mEyeDropCancelView.getContentView().findViewById(R.id.eye_txt);
            ttv.setTextColor(textColor);
        }
    }

    private void dismissEyeDropCancelView() {
        if (mEyeDropCancelView != null) {
            mEyeDropCancelView.dismiss();
        }
    }

    private Handler mPreviewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == EDIT_PREVIEW_GONE) {
                mPreviewViewContainer.animate().cancel();
                mPreviewViewContainer.animate().alpha(0).setDuration(Constant.PAINTING_EDIT_TOOL_ANIM_DURATION).setListener(mPreviewContainerAnimatorListener).start();
            } else if (msg.what == EDIT_BRUSH_TOOL_VISIBLE) {
                setBushAllToolVisible();
            } else if (msg.what == EDIT_TOOLTIP_VISIBLE) {
                Constant.PAINTER_TOOL_TIP = 0;
            } else if (msg.what == EDIT_ON_BACK_PRESS) {
                if (!mIsOnPause) {
                    getActivity().onBackPressed();
                } else {
                    mShouldBack = true;
                }
            } else if (msg.what == EDIT_UNDO) {
                mIsClickRedoOrUndo = true;
                mPaintStateListener.onRouteStateChanged();
                isOnClickRedoMenuItem();
                mPaintView.updateDrawing();
            } else if (msg.what == EDIT_REDO) {
                isOnClickRedoMenuItem();
                mIsClickRedoOrUndo = true;
                mPaintStateListener.onRouteStateChanged();
                mPaintView.updateDrawing();
            } else if (msg.what == EDIT_TOAST_MESSAGE) {
                if (mState == Constant.PAINTING_EDIT_TOAST_STATE_INSERT_FAIL) {
                    mInsertImgBtn.setEnabled(true);
                    //TODO
                    //mCopyBtn.setEnabled(true);
                    if (mCheckPaintingLayers) {
                        mChangeBgBtn.setEnabled(true);
                    }
                    Toast.makeText(getActivity(), getResources().getString(R.string.insert_pic_failed), Toast.LENGTH_SHORT).show();
                } else if (mState == Constant.PAINTING_EDIT_TOAST_STATE_COPY_FAIL) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.copy_fail), Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private void setPreviewContainerVisiable(boolean visible) {
        boolean isShow = mPreviewViewContainer.getVisibility() == View.VISIBLE;
        if (visible && !isShow) {
            setBrushToolVisibility(false);
            setEraserContainerVisible(false);
            setTexturePickerVisibility(false);
            mPreviewViewContainer.setVisibility(View.VISIBLE);
            mPreviewViewContainer.setAlpha(1);
        } else if (isShow && !visible) {
            mPreviewHandler.removeMessages(EDIT_PREVIEW_GONE);
            mPreviewHandler.sendEmptyMessageDelayed(EDIT_PREVIEW_GONE, 150);
        } else if (isShow && visible) {
            setBrushToolVisibility(false);
            setEraserContainerVisible(false);
            setTexturePickerVisibility(false);
            mPreviewViewContainer.setVisibility(View.VISIBLE);
            mPreviewViewContainer.setAlpha(1);
        }
        if (visible) {
            mPreviewView.invalidate();
        }
    }

    private void setPaperContainerVisibility(boolean visible) {
        if (mBgPaperContainer != null) {
            boolean isShow = mBgPaperContainer.getVisibility() == View.VISIBLE;
            if (visible && !isShow) {
                mBgPaperContainer.setVisibility(View.VISIBLE);
            } else if (isShow && !visible) {
                mBgPaperContainer.setVisibility(View.GONE);
            }
        }
    }

    private void setTexturePickerVisibility(boolean visible) {
        boolean isShow = mPaintTextureContainer.getVisibility() == View.VISIBLE;
        if (isShow && !visible) {// if current is show
            mPaintTextureContainer.setVisibility(View.GONE);
        } else if (!isShow && visible) {
            View vislbleView = getSecondaryVisibleView();
            if (vislbleView != null) {
                vislbleView.setVisibility(View.GONE);
                mPaintTextureContainer.setVisibility(View.VISIBLE);
                mBrushTool.updateItemView(R.id.action_texture);
            } else {
                mBrushTool.updateItemView(R.id.action_texture);
                mPaintTextureContainer.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setBrushAdjustContainerVisibility(boolean visible) {
        if (mBrushAdjustContainer != null) {
            boolean isShow = mBrushAdjustContainer.getVisibility() == View.VISIBLE;
            if (visible && !isShow) {
                mBrushAdjustContainer.setVisibility(View.VISIBLE);
                mBrushAdjustContainer.setBrushWidthSeekBarVisible(!mBrushTool.getItemFocus(R.id.action_texture));
            } else if (!visible && isShow) {
                mBrushAdjustContainer.setVisibility(View.GONE);
            } else if (isShow && visible) {
                mBrushAdjustContainer.setBrushWidthSeekBarVisible(!mBrushTool.getItemFocus(R.id.action_texture));
            }
        }
    }

    private void setCutFocus() {
        View visibleView = getSecondaryVisibleView();
        if (visibleView != null) {
            visibleView.setVisibility(View.GONE);
        }
        setBrushAdjustContainerVisibility(false);
        mBrushTool.updateItemView(R.id.action_cut);
    }

    private DialogInterface.OnClickListener mOnClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            save();
        }
    };

    private void save() {
        if (mLoadProgress == null) {
            mLoadProgress = ProgressHUD.create(getActivity());
        }
        mLoadProgress.dismiss();
        String str = getResources().getString(R.string.saving_painting);
        mLoadProgress.setLoadDesc(str);
        mLoadProgress.show();

        Bitmap paintingBrush = mPaintView.getMaskLayer();
        Bitmap painting = mPaintView.getPainting();
        if (paintingBrush != null && painting != null) {
            mPainting.mPainting = painting;
            mPainting.mPaintingBrush = Bitmap.createBitmap(paintingBrush);
        }
        mTheme = mPainting.mTheme;
        PaintingDatabase.getInstance().asyncSavePainting(getActivity().getApplicationContext(), mPainting, mCheckPaintingLayers, new PaintingDatabase.OnSavePaintingListener() {
            @Override
            public void setOnSavePaintingFinished(boolean success) {
                mLoadProgress.dismiss();
                if (success && mPaintView != null) {
                    mPaintView.onSave(true);
                } else {
                    Toast.makeText(getActivity(), getResources().getString(R.string.export_failed), Toast.LENGTH_SHORT).show();
                }
                mPreviewHandler.sendEmptyMessage(EDIT_ON_BACK_PRESS);
            }
        });
        mPaintView.onSave(true);
    }

    public boolean onBackPressed() {
        /*if (mNeedShowAd && SpotManager.getInstance(getActivity()).isSpotShowing()) {
            SpotManager.getInstance(getActivity()).hideSpot();
            return true;
        }*/

        if (getSecondaryVisibleView() != null) {
            getSecondaryVisibleView().setVisibility(View.GONE);
            return true;
        }
        if (mPaintView.getInCutCommit()) {
            mPaintView.commitCut();
            mPaintView.undo();
        }
        if (mPaintView != null) {
            if (!mPaintView.onBackPressed()) {
                setBushAllToolVisibility(false);
                if (mPainting != null && (mPaintView.needSave() || mTheme != mPainting.mTheme)) {
                    final CommonDialog dialog = new CommonDialog(getActivity());
                    dialog.setDesc(R.string.dialog_text);
                    dialog.setLefBtnText(R.string.dialog_no_savs);
                    dialog.setRightBtnText(R.string.dialog_save);
                    dialog.setOnRightClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onClick() {
                            dialog.dismiss();
                            save();
                        }
                    });
                    dialog.setOnLeftClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onClick() {
                            mPainting.mTheme = mTheme;
                            if (mPainting.mTheme < 0 || mPainting.mTheme > Theme.THEME_ALL - 1) {
                                mPaintView.changeBgColor(mPainting.mTheme);
                            } else {
                                mPaintView.changeBgDrawable(mPainting.mTheme, -1);
                            }
                            mPaintView.setPainting(mPainting.mTheme);
                            mPaintView.redoBitmap();
                            Bitmap paintingBrush = mPaintView.getMaskLayer();
                            if (paintingBrush != null) {
                                mPainting.mPaintingBrush = Bitmap.createBitmap(paintingBrush);
                            }
                            mPaintView.onSave(false);
                            getActivity().onBackPressed();
                        }
                    });
                    dialog.show();

                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            if (getActivity() != null) {
                                PainterUtils.clearTempFiles(getActivity());
                            }
                            return null;
                        }
                    }.execute();
                    return true;
                }
            } else {
                return true;
            }
            mColorPicker.setCurrentColor(mColorPicker.getResultColor(), false);
        }
        return false;
    }

    @Override
    public Loader<PaintingDatabase.PaintingEntry> onCreateLoader(int arg0, Bundle arg1) {
        return new PaintingEntryLoader(getActivity(), mId, mPaintView.getMaskLayer());
    }

    @Override
    public void onLoadFinished(Loader<PaintingDatabase.PaintingEntry> loader, PaintingDatabase.PaintingEntry painting) {
        if (painting != null) {
            mPainting = painting;
            mTheme = painting.mTheme;
            if (isDestroyActivity) {
                painting.mTheme = mCurrentTheme;
            } else {
                mCurrentTheme = painting.mTheme;
            }
            mPaintView.setPainting(painting.mTheme, mTheme, painting.mPaintingBrush, isDestroyActivity);
            applyBrushTypeSetting();
            mPaintView.checkPendingPlayback();
        } else {
            //TODO
        }
    }

    @Override
    public void onLoaderReset(Loader<PaintingDatabase.PaintingEntry> arg0) {
    }

    private void initBrushAndEraserImageView(int brushTpye) {
        boolean softEraser = mEraserType == Brush.BRUSH_SOFT_ERASRE;
        switch (brushTpye) {
            case Brush.BRUSH_PENCIL:
                if (mPencilBrush == null) {
                    mPencilBrush = (ImageView) mFragmentView.findViewById(R.id.brush_pencil);
                }
                break;
            case Brush.BRUSH_PEN:
                if (mPenBrush == null) {
                    mPenBrush = (ImageView) mFragmentView.findViewById(R.id.brush_pen);
                }
                break;
            case Brush.BRUSH_WATERCOLOR:
                if (mWcBrush == null) {
                    mWcBrush = (ImageView) mFragmentView.findViewById(R.id.brush_watercolor);
                }
                break;
            case Brush.BRUSH_CHALK:
                if (mChalkBrush == null) {
                    mChalkBrush = (ImageView) mFragmentView.findViewById(R.id.brush_chalk);
                }
                break;
            case Brush.BRUSH_MARKER:
                if (mMarkerBrush == null) {
                    mMarkerBrush = (ImageView) mFragmentView.findViewById(R.id.brush_marker);
                }
                break;
            case Brush.BRUSH_SOFT_CHARCOAL:
                if (mScBrush == null) {
                    mScBrush = (ImageView) mFragmentView.findViewById(R.id.brush_soft_charcoal);
                }
                break;
            case Brush.BRUSH_ERASER:
                if (mHardEraser == null) {
                    mHardEraser = (ImageView) mFragmentView.findViewById(R.id.hard_eraser);
                    mHardEraser.setTag(Brush.BRUSH_ERASER);
                    mHardEraser.setOnClickListener(this);
                }
                break;
            case Brush.BRUSH_SOFT_ERASRE:
                if (mSoftEraser == null) {
                    mSoftEraser = (ImageView) mFragmentView.findViewById(R.id.soft_eraser);
                    mSoftEraser.setTag(Brush.BRUSH_SOFT_ERASRE);
                    mSoftEraser.setOnClickListener(this);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_brush: {
                mPaintView.commitCut();
                mPaintView.commitInsert();
                mPaintView.commitTexture();
                for (int i = 0; i < Brush.BRUSH_COUNT; i++) {
                    initBrushAndEraserImageView(i);
                }
                if (!mBrushTool.getItemFocus(R.id.action_brush)) {
                    applyBrushTypeSetting();
                }
                if (mBrushToolContainer.getVisibility() == View.VISIBLE) {
                    boolean isShow = mBrushTypeContainer.getVisibility() == View.VISIBLE;
                    setBrushToolVisibility(!isShow);
                    setBrushAdjustContainerVisibility(true);
                }
                setTexturePickerVisibility(false);

                mPaintView.outFillTexture();
                mPaintView.outCut();
                break;
            }
            case R.id.action_eraser: {
                mPaintView.commitCut();
                mPaintView.commitInsert();
                mPaintView.commitTexture();
                for (int i = 0; i < Brush.BRUSH_COUNT; i++) {
                    initBrushAndEraserImageView(i);
                }
                if (!mBrushTool.getItemFocus(R.id.action_eraser)) {
                    applyEraserTypeSetting();
                }
                if (mBrushToolContainer.getVisibility() == View.VISIBLE) {
                    boolean isShow = mEraserContainer.getVisibility() == View.VISIBLE;
                    setEraserContainerVisible(!isShow);
                    setBrushAdjustContainerVisibility(true);
                }
                setTexturePickerVisibility(false);

                mPaintView.outFillTexture();
                mPaintView.outCut();
                break;
            }
            case R.id.action_cut:
                setTexturePickerVisibility(false);

                mPaintView.commitTexture();
                if (!mBrushTool.getItemFocus(R.id.action_cut)) {
                    mPaintView.initCut();
                }
                mPaintView.commitInsert();
                setCutFocus();
                mPaintView.outFillTexture();
                break;
            case R.id.action_color_picker: {
                mPaintView.commitCut();
                mPaintView.commitInsert();
                mPaintView.commitTexture();

                setTexturePickerVisibility(false);
                if (mBrushToolContainer.getVisibility() == View.VISIBLE) {
                    boolean isShow = mColorPickerContainer.getVisibility() == View.VISIBLE;
                    setColorPickerVisibility(!isShow);
                    setBrushAdjustContainerVisibility(true);
                    if (isShow) {
                        if (mBrushTool.getItemFocus(R.id.action_brush)) {
                            mBrushTool.updateItemView(R.id.action_brush);
                        }
                        if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                            mBrushTool.updateItemView(R.id.action_eraser);
                        }
                        if (mBrushTool.getItemFocus(R.id.action_texture)) {
                            mBrushTool.updateItemView(R.id.action_texture);
                        }
                        if (mBrushTool.getItemFocus(R.id.action_cut)) {
                            mBrushTool.updateItemView(R.id.action_cut);
                        }
                    }
                }
                break;
            }
            // eraser
            case R.id.hard_eraser:
            case R.id.soft_eraser:
                int eraserType = (Integer) v.getTag();
                if (mEraserType != eraserType) {
                    mEraserType = eraserType;
                    applyEraserTypeSetting();
                    mBrushTool.updateEraserIcon(mEraserType);
                    mPreviewView.invalidate();
                }
                break;

            case R.id.redo:
                if (mEyeDropperVisible) {
                    break;
                }

                if (mIsClickRedoOrUndo && mPaintView != null) {
                    mIsClickRedoOrUndo = false;
                    ThreadPool.getInstance().submit(new ThreadPool.Job<Void>() {
                        @Override
                        public Void run(ThreadPool.JobContext jc) {
                            mPaintView.redo();
                            return null;
                        }
                    }, new FutureListener<Void>() {
                        @Override
                        public void onFutureDone(Future<Void> future) {
                            mPreviewHandler.sendEmptyMessage(EDIT_REDO);
                        }
                    });
                }
                break;
            case R.id.undo:
                if (mEyeDropperVisible) {
                    break;
                }

                if (mIsClickRedoOrUndo) {
                    mIsClickRedoOrUndo = false;
                    mPaintView.setShowEyeDropperView(false);
                    setColorPickerVisibility(false);
                    ThreadPool.getInstance().submit(new ThreadPool.Job<Void>() {
                        @Override
                        public Void run(ThreadPool.JobContext jc) {
                            mPaintView.undo();
                            return null;
                        }
                    }, new FutureListener<Void>() {
                        @Override
                        public void onFutureDone(Future<Void> future) {
                            mPreviewHandler.sendEmptyMessage(EDIT_UNDO);
                        }
                    });
                }
                break;
            case R.id.insert_img:
                if (mEyeDropperVisible) {
                    break;
                }
                setTexturePickerVisibility(false);
                mPaintView.commitCut();
                mPaintView.commitTexture();
                if (getSecondaryVisibleView() != null) {
                    getSecondaryVisibleView().setVisibility(View.GONE);
                }
                if (!mPaintView.inInsertImage()) {
                    //gotoGalleryPickImage();
                    selectionPic();
                }
                break;
            case R.id.action_texture:
                if (mEyeDropperVisible) {
                    break;
                }

                mPaintView.commitCut();
                mPaintView.commitInsert();
                mPaintView.commitTexture();
                if (!mBrushTool.getItemFocus(R.id.action_texture)) {
                    applyTextureTypeSetting();
                }
                if (mBrushToolContainer.getVisibility() == View.VISIBLE) {
                    boolean isShow = mPaintTextureContainer.getVisibility() == View.VISIBLE;
                    setTexturePickerVisibility(!isShow);
                    setBrushAdjustContainerVisibility(false);
                }
                mPaintView.outCut();
                break;

            case R.id.back:
                getActivity().onBackPressed();
                break;

            case R.id.save:
                save();
                break;

            //copy
            /*case R.id.action_copy:
                // create a duplicate
                if (mPainting != null && (mPaintView.needSave() || mPaintView.getPaintMode() == PaintView.PAINT_MODE_EDIT)) {
                    if (mProgressDialog == null) {
                        mProgressDialog = new ProgressDialog(getActivity());
                    }
                    mProgressDialog.cancel();
                    String str = getResources().getString(R.string.copy_painting);
                    PainterUtils.setProgressDialog(mProgressDialog, str);
                    mProgressDialog.show();

                    Bitmap paintingBrush = mPaintView.getMaskLayer();
                    Bitmap painting = mPaintView.getPainting();
                    if (paintingBrush != null && painting != null) {
                        mPainting.mPainting = painting;
                        mPainting.mPaintingBrush = paintingBrush;
                    }
                    PaintingDatabase.getInstance().savePaintingAs(getActivity().getApplicationContext(), mPainting, mCheckPaintingLayers, new FutureListener<PaintingDatabase.PaintingEntry>() {
                        @Override
                        public void onFutureDone(Future<PaintingDatabase.PaintingEntry> future) {
                            PaintingDatabase.PaintingEntry paint = future == null ? null : future.get();
                            mProgressDialog.dismiss();
                            if (paint == null) {
                                mState = Constant.PAINTING_EDIT_TOAST_STATE_COPY_FAIL;
                                mPreviewHandler.sendEmptyMessage(EDIT_TOAST_MESSAGE);
                            }
                        }
                    });
                }
                break;*/

            case R.id.fill_bg:
                setTexturePickerVisibility(false);
                setFillBgContainerVisible(true);
                setBrushAdjustContainerVisibility(true);
                break;
            case R.id.switch_bg:
                setTexturePickerVisibility(false);
                setBrushAdjustContainerVisibility(false);
                if (mBgPaperContainer == null) {
                    mBgPaperContainer = (HorizontalScrollView) mFragmentView.findViewById(R.id.bg_paper_container);
                }
                if (mBgPaperPicker == null) {
                    mBgPaperPicker = (BackgroundPaperContainer) mFragmentView.findViewById(R.id.bg_paper_picker);
                    mBgPaperPicker.addChilds(BackgroundPaperContainer.EDIT_BACK_PAPER_COUNT, mBgPaperColorPicker.getResultColor());
                }
                mBgPaperPicker.setDefaultColor(mBgPaperColorPicker.getResultColor());
                mBgPaperPicker.setOnItemClickListener(new BackgroundPaperContainer.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view) {
                        int id = view.getId();
                        if (id == BackgroundPaperContainer.EDIT_BACK_PAPER_IDX) {
                            if (mPaintView.getBgColor() == mBgPaperPicker.getDefaultColor().getColor() && mPaintView.getBgShader() == null) {
                                setPaperContainerVisibility(false);
                                setBgPaperColorPickerVisibility(true);
                            } else {
                                int color = mBgPaperColorPicker.getResultColor();
                                mPaintView.changeBgColor(color);
                                mBgPaperColorPicker.setCurrentColor(color, false);
                                mPainting.mTheme = color;
                                mPaintView.setPainting(color);
                                if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                                    mPaintView.setBrush(mEraserType);
                                    mPreviewView.setBrush(mPaintView.getBrush());
                                }
                            }
                        } else {
                            if (mPainting.mTheme != id) {
                                PaintEditFragment.this.mPaintView.onBackPressed();
                                int[] location = new int[2];
                                view.getLocationInWindow(location);
                                float center = location[0] + view.getWidth() / 2;
                                mPaintView.changeBgDrawable(id, center);
                                mPainting.mTheme = id;
                                mPaintView.setPainting(id);
                            }
                            if (mBrushTool.getItemFocus(R.id.action_eraser)) {
                                mPaintView.setBrush(mEraserType);
                                mPreviewView.setBrush(mPaintView.getBrush());
                            }
                        }
                    }
                });

                setBrushToolVisibility(false);
                setColorPickerVisibility(false);
                setBgPaperColorPickerVisibility(false);
                setEraserContainerVisible(false);
                setPaperContainerVisibility(true);
                break;
        }
    }

}
